﻿<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { useAuthStore } from '../stores/auth';
import {
  fetchCourseDetail,
  fetchCourseTasks,
  fetchCourseComments,
  createCourseComment,
} from '../api/demo';

const route = useRoute();
const authStore = useAuthStore();

const loading = ref(true);
const course = ref(null);
const tasks = ref([]);
const comments = ref([]);

const commentFormRef = ref();
const commentLoading = ref(false);
const commentForm = reactive({
  body: '',
});

const activeTab = ref('intro');

const courseId = computed(() => Number(route.params.id));

const categoryName = computed(() => {
  const detail = course.value;
  if (!detail) return '课程类别';
  return (
    detail.categoryTitle ||
    detail.categoryname ||
    detail.category ||
    detail.category_name ||
    (detail.categoryid ? `类别ID：${detail.categoryid}` : '课程类别')
  );
});

const formatDateTime = (value) => {
  if (!value) return '待定';
  const date = dayjs(value);
  if (!date.isValid()) return '待定';
  return date.format('YYYY年MM月DD日 HH:mm');
};

const loadCourseDetail = async () => {
  if (!courseId.value) {
    ElMessage.error('课程ID无效');
    return;
  }
  try {
    loading.value = true;
    const [detail, taskList, commentList] = await Promise.all([
      fetchCourseDetail(courseId.value),
      fetchCourseTasks(courseId.value),
      fetchCourseComments(courseId.value),
    ]);
    course.value = detail;
    tasks.value = Array.isArray(taskList) ? taskList : [];
    comments.value = Array.isArray(commentList) ? commentList : [];
  } catch (error) {
    ElMessage.error(error?.message || '加载课程信息失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handleResetComment = () => {
  commentForm.body = '';
  commentFormRef.value?.clearValidate();
};

const handleSubmitComment = () => {
  if (!commentFormRef.value) return;
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录后再发表评论');
    return;
  }
  commentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      commentLoading.value = true;
      await createCourseComment({
        body: commentForm.body,
        userid: authStore.user?.id,
        articleid: courseId.value,
      });
      ElMessage.success('评价发布成功');
      handleResetComment();
      const list = await fetchCourseComments(courseId.value);
      comments.value = Array.isArray(list) ? list : [];
    } catch (error) {
      ElMessage.error(error?.message || '发布评价失败，请稍后重试');
    } finally {
      commentLoading.value = false;
    }
  });
};

const commentRules = {
  body: [{ required: true, message: '请输入课程评价内容', trigger: 'blur' }],
};

const hasEnoughTasks = computed(() => tasks.value.length >= 2);

watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      loadCourseDetail();
    }
  }
);

onMounted(() => {
  if (courseId.value) {
    loadCourseDetail();
  }
});
</script>

<template>
  <div class="detail-page">
    <el-breadcrumb separator="/" class="detail-page__breadcrumb">
      <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>课程详情</el-breadcrumb-item>
      <el-breadcrumb-item>{{ course?.title || '加载中' }}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-skeleton :loading="loading" animated :rows="6">
      <template #template>
        <el-skeleton-item variant="h1" style="width: 60%; height: 36px; margin-bottom: 20px" />
        <el-skeleton-item variant="text" style="margin-bottom: 12px" />
        <el-skeleton-item variant="text" style="width: 80%; margin-bottom: 12px" />
        <el-skeleton-item variant="text" style="width: 50%; margin-bottom: 24px" />
        <el-skeleton-item variant="rect" style="width: 100%; height: 260px" />
      </template>
      <template #default>
        <el-card class="detail-card" shadow="hover">
          <div class="detail-card__header">
            <div>
              <h1>{{ course?.title }}</h1>
              <p>{{ course?.body }}</p>
            </div>
            <el-tag size="large" type="success">精品课程</el-tag>
          </div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="任课老师">{{ course?.teachername || '待定' }}</el-descriptions-item>
            <el-descriptions-item label="开课时间">{{ formatDateTime(course?.startTime) }}</el-descriptions-item>
            <el-descriptions-item label="结课时间">{{ formatDateTime(course?.endTime) }}</el-descriptions-item>
            <el-descriptions-item label="所属类别">{{ categoryName }}</el-descriptions-item>
          </el-descriptions>
          <el-tabs v-model="activeTab" class="detail-tabs">
            <el-tab-pane label="课程内容" name="intro">
              <h3>课程简介</h3>
              <p class="tab-text">{{ course?.body || '暂无课程介绍' }}</p>
              <el-alert
                v-if="!hasEnoughTasks"
                title="建议为课程添加至少两个任务项，便于学生循序渐进学习。"
                type="warning"
                show-icon
                class="detail-alert"
              />
              <h3>课程任务</h3>
              <el-empty v-if="!tasks.length" description="该课程尚未添加任务，请管理员尽快补充" />
              <el-timeline v-else>
                <el-timeline-item
                  v-for="task in tasks"
                  :key="task.id"
                  :timestamp="task.addedTime ? formatDateTime(task.addedTime) : ''"
                  placement="top"
                >
                  <el-card shadow="never" class="task-card">
                    <h4>{{ task.title }}</h4>
                    <p>{{ task.body }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-tab-pane>
            <el-tab-pane label="课程评价" name="comments">
              <div class="comment-section">
                <h3>已有评价</h3>
                <el-empty v-if="!comments.length" description="暂时还没有评价，快来抢沙发" />
                <el-card
                  v-for="comment in comments"
                  :key="comment.id"
                  shadow="never"
                  class="comment-card"
                >
                  <div class="comment-card__header">
                    <span class="comment-card__author">发布人：{{ comment.username || comment.realName || '匿名用户' }}</span>
                    <span class="comment-card__time">{{ formatDateTime(comment.addedTime) }}</span>
                  </div>
                  <p>{{ comment.body }}</p>
                </el-card>

                <h3 class="comment-form__title">发布评价</h3>
                <el-alert
                  v-if="!authStore.isLoggedIn"
                  title="登录后才能发布评价，点击右上角登录按钮进入系统"
                  type="info"
                  show-icon
                  class="detail-alert"
                />
                <el-form
                  ref="commentFormRef"
                  :model="commentForm"
                  :rules="commentRules"
                  label-width="0"
                  size="large"
                >
                  <el-form-item prop="body">
                    <el-input
                      v-model="commentForm.body"
                      type="textarea"
                      :rows="4"
                      maxlength="500"
                      show-word-limit
                      placeholder="请填写对课程的理解、建议或学习体验"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" :loading="commentLoading" @click="handleSubmitComment">
                      发布评价
                    </el-button>
                    <el-button @click="handleResetComment">清空</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </template>
    </el-skeleton>
  </div>
</template>

<style scoped>
.detail-page {
  max-width: 1080px;
  margin: 0 auto;
}

.detail-page__breadcrumb {
  margin-bottom: 16px;
}

.detail-card {
  border-radius: 16px;
}

.detail-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  margin-bottom: 24px;
}

.detail-card__header h1 {
  font-size: 32px;
  margin-bottom: 12px;
}

.detail-card__header p {
  color: #4f5a70;
  line-height: 1.7;
}

.detail-tabs {
  margin-top: 24px;
}

.tab-text {
  color: #4f5a70;
  line-height: 1.8;
  margin-bottom: 24px;
  white-space: pre-wrap;
}

.detail-alert {
  margin-bottom: 20px;
}

.task-card h4 {
  font-size: 18px;
  margin-bottom: 10px;
}

.task-card p {
  color: #4f5a70;
  line-height: 1.6;
}

.comment-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.comment-card {
  border-radius: 12px;
}

.comment-card__header {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #8c8c8c;
  margin-bottom: 10px;
}

.comment-form__title {
  margin: 0;
}

@media (max-width: 768px) {
  .detail-card__header {
    flex-direction: column;
    align-items: flex-start;
  }
  .detail-card__header h1 {
    font-size: 26px;
  }
}
</style>
